package com.hc.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.codec.digest.DigestUtils;
 /**
  * MD5校验文件
  * @author young
  *
  */
public class MD5Util {    
     /**
      * 通过uid+当前时间生成hash码;
      * @param uid
      * @param chapterId
      * @return
      */
	public static String generatorKey(int uid){
		String key = uid+OtherUtils.getCurrentDateNum();
		ByteArrayInputStream in = new ByteArrayInputStream(key.getBytes());
		try {
			key = getStringHash(in);
		} catch (Exception e) {
			LoggerUtil.error(e);
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
		}
		return key;
	}
    /**
     * 获取hash码
     * @param in
     * @return
     * @throws Exception
     */
    public static String getStringHash(InputStream in)    
            throws Exception {    
        return  DigestUtils.md5Hex(in);
    } 
    /**
     * 获取hash码
     * @param data
     * @return
     * @throws Exception
     */
    public static String getStringHash(String data)    
            throws Exception {    
        return  DigestUtils.md5Hex(data);
    } 
    /**
     * 验证书本对应hash是否一致
     * @param newBook
     * @param oldBook
     * @return
     */
    public static Boolean valid(String newBook,String oldBook){
    	InputStream inNewBook = null;
    	InputStream inOldBook = null;
    	try {
    		inNewBook = new ByteArrayInputStream(newBook.getBytes());
    		inOldBook = new ByteArrayInputStream(oldBook.getBytes());
			if (getStringHash(inNewBook).equals(getStringHash(inOldBook))){
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			LoggerUtil.error(e);
			return false;
		} finally {
			try {
				inNewBook.close();
				inOldBook.close();
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
		}
    }
} 
